<template>
	<view class="container">
		<div class="user-info card-style">
			<u-avatar :src="nowUser.avatar" size="45"></u-avatar>
			<div class="username">{{nowUser.username}}</div>
			<div class="upload-btn">
				<u-upload :fileList="fileList" @afterRead="afterRead" multiple :maxCount="2" :previewImage="false">
					<u-button type="primary" text="上传眼底图像" size="small"></u-button>
				</u-upload>
			</div>
		</div>

		<div class="personalized-advice card-style">
			<text class="healthy-title">👀上传眼底图像，解锁个性化健康管理</text>
			<u-collapse ref="collapse" class="healthy-detail" :value="nowCollapse">
				<u-collapse-item title="您的眼底健康评分及个性化眼底健康管理建议" name="healthy">
					<text>{{suggestion}}</text>
				</u-collapse-item>
			</u-collapse>
			<u-cell-group>
				<u-cell icon="list-dot" title="诊断记录" :isLink="true" arrow-direction="right"
					@click="navigateToTarget('诊断记录')"></u-cell>
				<u-cell icon="edit-pen" title="快速自查" :isLink="true" arrow-direction="right"
					@click="navigateToTarget('快速自查')"></u-cell>
				<u-cell icon="grid" title="疾病科普" :isLink="true" arrow-direction="right"
					@click="navigateToTarget('疾病科普')"></u-cell>
			</u-cell-group>
		</div>

		<div class="news-list card-style">
			<div class="news-title">📰{{newsTitle}}</div>
			<div class="news-line">
				<u-line></u-line>
			</div>
			<div v-for="(item,index) in newsList" :key="index">
				<div class="news-box" @click="jumpToNewsDetail(item.url)">
					<div class="news-image-box">
						<image :src="item.thumbnail_pic_s" class="news-image"></image>
					</div>
					<div class="news-detail">
						<u--text :lines="2" :text="item.title" type="primary" bold size="17"></u--text>
						<div class="news-info">
							<u--text :lines="1" type="info" :text="'作者：' + item.author_name"></u--text>
							<u--text :lines="1" type="info" :text="'专栏：' + item.category"></u--text>
						</div>
						<u--text :lines="1" type="info" :text="'发表日期：' + item.date"></u--text>
					</div>
				</div>
				<u-divider text="分割线" :dot="true"></u-divider>
			</div>
		</div>
		<u-toast ref="uToast"></u-toast>
	</view>
</template>

<script>
	import {
		getUserInfo
	} from '../../../api/login';
	import io from '@hyoga/uni-socket.io';
	export default {
		data() {
			return {
				// 当前展开的面板 用于控制个性化建议生成完成后弹出面板
				nowCollapse: [],
				fileList: [],
				socket: null,
				// 大模型回答及流式回答要用的下标
				answer: '',
				idx: '',
				nowUser: {},
				count: 5,
				score: 0,
				newsTitle: '',
				// 个性化健康管理建议
				suggestion: '请您先上传左右眼底图像。',
				newsList: [{
						"uniquekey": "ff149b33f4fc9fe577c07a45ef6616da",
						"title": "GRANVER：前沿科技赋能精准抗老，天然成分开启健康风尚",
						"date": "2025-03-17 11:32:00",
						"category": "健康",
						"author_name": "鲁网",
						"url": "https://mini.eastday.com/mobile/250317113205481733730.html",
						"thumbnail_pic_s": "https://dfzximg02.dftoutiao.com/news/20250317/20250317113205_25cc966820b28ff5f7770498867afe67_1_mwpm_03201609.jpeg",
						"thumbnail_pic_s02": "https://dfzximg02.dftoutiao.com/news/20250317/20250317113205_25cc966820b28ff5f7770498867afe67_2_mwpm_03201609.jpeg",
						"is_content": "1"
					},
					{
						"uniquekey": "b1e90f1c6b97362774a230590066692e",
						"title": "农行安徽分行：金融助春耕，科技产好粮",
						"date": "2025-03-17 11:32:00",
						"category": "健康",
						"author_name": "人民网－安徽频道，供稿：人民资讯",
						"url": "https://mini.eastday.com/mobile/250317113203987302096.html",
						"thumbnail_pic_s": "https://dfzximg02.dftoutiao.com/news/20250317/20250317113203_cbe02355c93836a3b3bace8844c87aba_1_mwpm_03201609.jpeg",
						"thumbnail_pic_s02": "https://dfzximg02.dftoutiao.com/news/20250317/20250317113203_cbe02355c93836a3b3bace8844c87aba_2_mwpm_03201609.jpeg",
						"thumbnail_pic_s03": "https://dfzximg02.dftoutiao.com/news/20250317/20250317113203_cbe02355c93836a3b3bace8844c87aba_3_mwpm_03201609.jpeg",
						"is_content": "1"
					},
					{
						"uniquekey": "be4219d8bff461466b4ef62e3851dd6c",
						"title": "NYO3磷虾油亮相 Vitafoods Asia：乘势东南亚，进阶 Omega-3 新征程",
						"date": "2025-03-17 11:28:00",
						"category": "健康",
						"author_name": "鲁网",
						"url": "https://mini.eastday.com/mobile/250317112829632898547.html",
						"thumbnail_pic_s": "https://dfzximg02.dftoutiao.com/news/20250317/20250317112829_c646afd6bb7780668f647164d87cc926_1_mwpm_03201609.jpeg",
						"thumbnail_pic_s02": "https://dfzximg02.dftoutiao.com/news/20250317/20250317112829_c646afd6bb7780668f647164d87cc926_2_mwpm_03201609.jpeg",
						"thumbnail_pic_s03": "https://dfzximg02.dftoutiao.com/news/20250317/20250317112829_c646afd6bb7780668f647164d87cc926_3_mwpm_03201609.jpeg",
						"is_content": "1"
					},
					{
						"uniquekey": "3124e8517d992c7c93467897c12c0c57",
						"title": "东城中医医院特聘专家赵颂杰：无痛腹针精准治疗肩颈痛",
						"date": "2025-03-17 11:06:00",
						"category": "健康",
						"author_name": "北青网",
						"url": "https://mini.eastday.com/mobile/250317110659357705840.html",
						"thumbnail_pic_s": "https://dfzximg02.dftoutiao.com/news/20250317/20250317110659_6cd84156b94592319c3df28432e8c571_1_mwpm_03201609.jpeg",
						"is_content": "1"
					},
					{
						"uniquekey": "52434c089bd05b686d5976608ab06466",
						"title": "济南鲁能希尔顿酒店及公寓硬壳美食节启幕——開·全日餐厅匠心呈现、寻味本真",
						"date": "2025-03-17 10:56:00",
						"category": "健康",
						"author_name": "鲁网",
						"url": "https://mini.eastday.com/mobile/250317105620545714180.html",
						"thumbnail_pic_s": "https://dfzximg02.dftoutiao.com/news/20250317/20250317105620_a3b9ba820b108b17c209b2d08643b77c_1_mwpm_03201609.jpeg",
						"thumbnail_pic_s02": "https://dfzximg02.dftoutiao.com/news/20250317/20250317105620_a3b9ba820b108b17c209b2d08643b77c_2_mwpm_03201609.jpeg",
						"thumbnail_pic_s03": "https://dfzximg02.dftoutiao.com/news/20250317/20250317105620_a3b9ba820b108b17c209b2d08643b77c_3_mwpm_03201609.jpeg",
						"is_content": "1"
					}
				],
			}
		},
		mounted() {
			this.getNewsTitle();
			this.getNews();
			this.getNowUserInfo();
			this.nowCollapse = []
		},
		onHide() {
			// 离开时断开Socketio连接
			if (this.socket !== null) {
				this.socket.disconnect();
			}
		},
		methods: {
			async afterRead(event) {
				let lists = [].concat(event.file);
				if (lists.length !== 2) {
					this.$refs.uToast.show({
						type: 'error',
						message: "请上传一对眼底图像!",
						position: "top"
					});
					return;
				}

				// 记录下上传成功的图片数量
				let count = 0;
				// 上传的左右眼文件名称
				let filenames = ['left_image.jpg', 'right_image.jpg']
				for (let i = 0; i < lists.length; i++) {
					this.fileList.push(lists[i])
					uni.uploadFile({
						url: `https://yiyuy.mynatapp.cc/model/uniappUploadImage?filename=${filenames[i]}`,
						filePath: lists[i].url,
						name: "file",
						success: (response) => {
							console.log(response)
							if (response.statusCode !== 200) {
								this.$refs.uToast.show({
									type: 'error',
									message: "图片上传失败",
									position: "top"
								});
							} else {
								count++;
								if (count === 2) {
									this.$refs.uToast.show({
										type: 'success',
										message: "图片上传成功,个性化健康管理生成中...",
										position: "top"
									});

									// 图片上传完毕 询问大模型
									// 做一个过度
									let that = this;
									this.suggestion = '正在为您生成个性化报告'
									let dotInterval = setInterval(() => {
										that.suggestion += '.'
										that.$nextTick(() => {
											that.$refs.collapse.init();
										})
									}, 1000)

									let question =
										'这是一对眼底图像，请你为该患者的眼底健康进行评分，评分范围为0星~5星，同时给出个性化眼底健康管理建议，按照您的眼底健康评分：x星，以下是您的个性化眼底健康管理建议的格式回答，记住你不需要说其他话，只需要回答我的问题.'

									setInterval(function() {
										if (that.idx < that.answer.length) {
											that.suggestion = that.answer.slice(0, that.idx + 1);
											that.idx++;
										}
										that.$nextTick(() => {
											that.$refs.collapse.init();
										})
									}, 50)

									this.socket = io('https://yiyuy.mynatapp.cc/spark', {
										query: {
											"question": question,
											"leftFilename": filenames[0],
											"rightFilename": filenames[1],
										},
										transports: ['websocket'],
										timeout: 5000,
									});

									// 连接成功后 开始正式显示内容
									this.socket.on('connect', () => {
										this.suggestion = ''
										this.nowCollapse = ['healthy']
										clearInterval(dotInterval)
									});

									// 监听服务器事件
									this.socket.on('server_response', (message) => {
										// 收到服务器推送的消息，可以跟进自身业务进行操作
										if (message.data === '[over]') {
											this.socket.disconnect()
										} else {
											this.answer += message.data;
										}
									});
									
									this.socket.emit('startTalk',{question: question,leftFilename:filenames[0],rightFilename: filenames[1]})
								}
							}
						},
						fail: (error) => {
							console.log(error)
							this.$refs.uToast.show({
								type: 'error',
								message: "请求失败",
								position: "top"
							});
						}
					})
				}
			},
			// 跳转到内部页面
			navigateToTarget(title) {
				if (title === '诊断记录') {
					uni.navigateTo({
						url: '/pages/index/history/history'
					})
				}
				if (title === '快速自查') {
					uni.navigateTo({
						url: '/pages/index/selfTest/selfTest'
					})
				}
				if (title === '疾病科普') {
					uni.navigateTo({
						url: '/pages/index/diseaseScience/diseaseScience'
					})
				}
			},
			// 跳转到外部新闻链接
			jumpToNewsDetail(url) {
				void plus.runtime.openWeb(url);
			},
			// 获取用户名
			getNowUserInfo() {
				getUserInfo().then((res) => {
					if (res.code === 200) {
						this.nowUser = res.data;
					} else {
						this.$refs.uToast.show({
							type: 'error',
							message: "获取个人信息失败",
							position: "top"
						});
					}
				})
			},
			getNewsTitle() {
				let now = new Date();
				let hour = now.getHours()
				if (hour < 6) {
					this.newsTitle = '凌晨好，来看看有什么最新要闻吧。'
				} else if (hour < 9) {
					this.newsTitle = '早上好，来看看有什么最新要闻吧。'
				} else if (hour < 12) {
					this.newsTitle = '上午好，来看看有什么最新要闻吧。'
				} else if (hour < 14) {
					this.newsTitle = '中午好，来看看有什么最新要闻吧。'
				} else if (hour < 17) {
					this.newsTitle = '下午好，来看看有什么最新要闻吧。'
				} else if (hour < 19) {
					this.newsTitle = '傍晚好，来看看有什么最新要闻吧。'
				} else if (hour < 22) {
					this.newsTitle = '晚上好，来看看有什么最新要闻吧。'
				} else {
					this.newsTitle = '夜里好，来看看有什么最新要闻吧。'
				}
			},
			getNews() {
				const apiUrl = 'http://v.juhe.cn/toutiao/index';
				const apiKey = '69646436a9eafad1570bed9ea358e8f1';
				const requestParams = {
					key: apiKey,
					type: 'jiankang',
					page: 1,
					page_size: 5,
				};
				uni.request({
					url: apiUrl,
					data: requestParams,
					method: 'GET',
					success: (response) => {
						console.log(response)
						if (response.statusCode === 200) {
							this.newsList = response.data.result.data;
						}
					},
					fail: (error) => {
						this.$refs.uToast.show({
							type: 'error',
							message: "获取每日新闻失败",
							position: "top"
						});
					}
				})

			}
		}
	}
</script>

<style>
	@keyframes moveIn {
		0% {
			opacity: 0;
			transform: translateY(12px);
		}

		100% {
			opacity: 1;
			transform: translateY(0);
		}
	}

	.card-style {
		border-radius: 4px;
		border: 1px solid #ebeef5;
		background-color: #fff;
		color: #303133;
		transition: .3s;
		box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);
		animation: moveIn .3s cubic-bezier(.4, 0, .2, 1) forwards;
	}

	.container {
		width: 100%;
		height: 100%;
	}

	.user-info {
		width: 100%%;
		display: flex;
		align-items: center;
		padding: 10px;
	}

	.username {
		font-size: 25px;
		margin-left: 10px;
	}

	.upload-btn {
		margin-left: auto;
	}

	.personalized-advice {
		padding-top: 10rpx;
		width: 100%;
		margin: 5px auto;
	}

	.healthy-title {
		font-size: 17px;
		font-weight: bold;
	}

	.healthy-detail {
		margin-top: 5px;
	}

	.news-list {
		padding-top: 10rpx;
		margin-top: 5px;
	}

	.news-title {
		width: 100%;
		font-size: 17px;
		font-weight: bold;
		margin-bottom: 5px;
		display: flex;
		align-items: center;
	}

	.news-line {
		margin-top: 10px;
		margin-bottom: 10px;
		width: 100%;
	}

	.news-detail {
		margin-left: 10rpx;
	}

	.news-box {
		display: flex;
		width: 100%;
	}

	.news-image-box {
		width: 280rpx;
		height: 200rpx;
	}

	.news-image {
		width: 260rpx;
		height: 200rpx;
		border-radius: 2px;
	}

	.news-info {
		display: flex;
	}

	/* 高度自适应 */
	.u-collapse-item /deep/ .u-collapse-item__content__text {
		height: auto;
	}
</style>